<template>
  <div>
    <el-form label-width="80px">
      <el-form-item label="SPU名称">xxx</el-form-item>
      <el-form-item label="SKU名称" v-model="skuParams.skuName">
        <el-input placeholder="请你输入名称呢过"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)"  v-model="skuParams.price">
        <el-input type="number" placeholder="价格(元)"></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)"  v-model="skuParams.weight">
        <el-input type="number" placeholder="重量(千克)"></el-input>  
      </el-form-item>
      <el-form-item label="规格描述"  v-model="skuParams.skuDesc">
        <el-input type="textarea" placeholder="规格描述"></el-input>
      </el-form-item>
       <!--平台属性-->
    <el-form-item label="平台属性" >
      <!--行内form:因为一行放置多个select-->
      <el-form :inline="true">
        <el-form-item :label="attr.attrName"  v-for="(attr, index) in attrArr" :key="attr.id" >
          <el-select v-model="attr.attrIdAndValueId">
            <el-option :label="item.valueName" :value="`${attr.id}:${item.id}`" v-for="(item, index) in attr.attrValueList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
       
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <!--行内form:因为一行放置多个select-->
      <el-form :inline="true">
        <el-form-item 
      :label="sale.saleArrName"
        v-for="(sale,index) in saleArr"
        :key="sale.id"
        >
          <el-select>
            <el-option :label="item.saleAttrValueName"
              :value="`${saleAttr.id}:${item.id}`"
              v-for="(item, index) in saleAttr"
              :key="item.id"></el-option>
          </el-select>
          <!-- .spuSaleAttrValueList -->
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片名称">
      <el-table border :data="imgAttr" ref="tableRef">
        <el-table-column width="80" type="selection"></el-table-column>
        <el-table-column label="图片">
          <template #="{ row, $index }">
            <img
              :src="row.imgUrl"
              alt="图片没了"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" v-if="row.isChecked==1">默认</el-button>
            <el-button type="info" size="small"  v-else
              @click="changeChecked(row)">设置默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button size="default"  @click="emit('changeScene', { scenes: 0, flag: '' })">取消</el-button>
    </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { reqAttrList, reqImageList, reqAllAttr,reqAddSku } from "@/api/product/spu/spu";
import { ElMessage } from "element-plus";
//储存品台属性
let attrArr = ref([]);
//储存照片墙属性
let imgAttr = ref([]);
//储存全部销售属性
let saleArr = ref([]);
//收集添加SKU参数
let skuParams=ref({
 //父组件传递过来参数
 category3Id: 0, //三级分类的ID
  spuId: 0, //SPU的ID
  tmId: 0, //spu的品牌的ID
   //v-model收集
  skuName: "", //sku的名字
  price: 0, //sku的价格
  weight: "", //sku的重量
  skuDesc: "", //sku的描述
  skuDefaultImg: "", //默认图片地址
  skuAttrValueList: [
    //平台属性
    // {
    //   attrId: 0, //属性的id
    //   valueId: 0, //属性值的ID
    // },
  ],
  skuSaleAttrValueList: [
    //销售属性
    // {
    //   saleAttrId: 0,
    //   saleAttrValueId: 0,
    // },
  ], 
})
//子组件和父组件方法
const initSku = async (
  c1Id: number | string,
  c2Id: number | string,
  spu: any
) => {
  //收集三级分类的ID|SPUID|TMID
  skuParams.value.category3Id=spu.category3Id;
  skuParams.value.spuId=spu.id
  skuParams.value.tmId=spu.tmId
  let result1 = await reqAttrList(c1Id, c2Id, spu.category3Id);
  let result2 = await reqImageList(spu.id);
  let result3 = await reqAllAttr(spu.id);
  attrArr.value = result1;
  //照片墙
  imgAttr.value = result2;
  if (imgAttr.value.length == 0) return;
  //由于服务器返回的数据没有控制默认按钮标记：只能自己手动添加
  //添加一个字段:isChecked 1 默认  0不是默认
  imgAttr.value[0].isChecked = 1;
  setTimeout(() => {
    tableRef.value.toggleRowSelection(imgAttr.value[0], true);
    skuParams.value.skuDefaultImg = imgAttr.value[0].imgUrl;
  }, 0);
  //添加isChecked = 0；
  for (var i = 0; i < imgAttr.value.length - 1; i++) {
    if (i > 0) {
      imgAttr.value[i].isChecked = 0;
    }
  }
  saleArr.value = result3;
};
//切换checked
const changeChecked = (row) => {
  //全部图片先变成0
  imgAttr.value.forEach((item) => {
    item.isChecked = 0;
    //全部table复选框不勾选
    tableRef.value.toggleRowSelection(item, false);
  });
  //选中图片设置为默认
  row.isChecked = 1;
  //table组件实例:toggleRowSelection 设置某一行能否被选中
  tableRef.value.toggleRowSelection(row, true);
  //收集服务器需要携带的参数
  skuParams.value.skuDefaultImg = row.imgUrl;
};
//保存按钮
const save=async ()=>{
    //整理参数
  //整理平台属性
  skuParams.value.skuAttrValueList = attrArr.value.reduce((prev, next) => {
    //next:当前平台属性数组里面每一个元素
    //判断：当前品台属性对象是否有attrIdAndValueId属性，如果有说明用户在这个属性里面勾选了
    if (next.attrIdAndValueId) {
      //把字符串切割为数组
      const [attrId, valueId] = next.attrIdAndValueId.split(":");
      //整理成对象添加数组里面:对象，分别存储属性ID与属性值的ID
      prev.push({ attrId, valueId });
    }
    return prev;
  }, []);
  //整理销售属性
  skuParams.value.skuAttrValueList=saleArr.value.reduce((prev,next)=>{
    if(next.saleAttrValueId){
      const [saleAttrId,saleAttrValueId]=
      next.saleAttrIdAndValueId.split(":");
      prev.push({ saleAttrId, saleAttrValueId });
    }
    return prev
  },[])
    //发请求+添加SKU

    try {
    await reqAddSku(skuParams.value);
    //请求成功:通知父组件切换场景0 + 提示信息
    //提示框
    ElMessage({
      type: "success",
      message: "添加SKU成功",
    });
    emit("changeScene", { scenes: 0, flag: "" });
  } catch (error) {
    ElMessage({
      type: "error",
      message: "添加SKU失败",
    });
  }

}
//重置数据方法
const resetData = ()=>{
  attrArr.value = [];
  saleArr.value = [];
  imgAttr.value = [];
  skuParams.value = {};
}

//取消的方法
const cancel = ()=>{
  //触发自定义事件
  emit('changeScene',{scenes:0,flag:''});
  resetData();
}
defineExpose({
  initSku,
});
let emit=defineEmits(['changeScene"'])
</script>

<style scoped>
</style>